#!/usr/bin/env ruby
# frozen_string_literal: true

require "json"

len = $stdin.read(4).unpack1("L")
data = JSON.parse($stdin.read(len))
url = data["url"]
options = data["options"] || []

args = %w[--no-terminal]
args.push(*options)

# HACK(ww): On macOS, graphical applications inherit their path from `launchd`
# rather than the default path list in `/etc/paths`. `launchd` doesn't include
# Homebrew in its default list, which means that any installations
# of MPV and/or youtube-dl under that prefix aren't visible when spawning
# from, say, Firefox. The real fix is to modify `launchd.conf`, but that's
# invasive and maybe not what users want in the general case.
# Hence this nasty hack.
ENV["PATH"] = "/opt/homebrew/bin:/usr/local/bin:#{ENV['PATH']}" if RUBY_PLATFORM =~ /darwin/

pid = spawn "mpv", *args, "--", url, in: :close, out: "/dev/null", err: "/dev/null"

Process.detach pid
